<?php
namespace App\Http\Controllers\Admin;


use Illuminate\Support\Facades\DB;
use  Illuminate\Support\Facades\Input; //获取表单数据
use  App\Models\Login;  //获取登录用户表的信息
use  App\Models\User;  //获取登录用户表的信息
use  App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;  //用于验证表单
class LoginController extends Controller
{
    /*
     * 系统登录后台若没有表单提交则展示登录页面
     * 存在表单提交则进行验证
     */

    public function login(){

        if(Input::all()){
            $data = Input::all();//获取用户输入的信息
            //var_dump($data);exit
            //验证表单
            $rules =['user'=>'required','pass'=>'required|numeric'];
            $message=['user.required'=>'用户名不能为空！！','pass.required'=>'密码不能为空！！','pass.numeric'=>'密码只能是数字！！'];
            $validator = Validator::make($data,$rules,$message);
           // var_dump($validator);
            if($validator->fails()){
                return redirect('/admin/login')->with('errors',$validator->errors()->all());
            };
           //表单验证end
            $userinfo = Login::where('user_name', $data['user'])->first();//获取数据库的用户信息
            if(!empty($userinfo)){
                $userinfo = $userinfo->toArray();
                if($userinfo['user_pass'] == $data['pass']){
                    //登录成功，写入session 进入blog后台页面
                    session(['userinfo' => $userinfo]);
                    //var_dump(session('userinfo'));
                    return  redirect('/admin/index');
                    // return redirect('index11');
                }else{
                    return redirect('/admin/login')->with('message','密码不正确，请输入正确的用密码！'); //message写到session里面了
                }
            }else{
                return redirect('/admin/login')->with('message','用户名不正确，请输入正确的用户名！');
            }
        }else{
            return view('/admin/login');
        }

    }

    public function loginout()
    {
        session(['userinfo'=>null]);  //清除session
        return redirect('admin/login');
    }
    /*
     *注册用户
     **/
    public function register()
    {
        if($data = Input::except('_token')){

        //注册 校验数据
            //end
            User::insert($data);
            return redirect('/admin/login')->with('message','注册用户成功！');
        }else{
            return view('admin/register');
        }

    }

}
